package com.linefly.online_car;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.linefly.online_car.Custom.MyLoading;
import com.linefly.online_car.Custom.ReLogin;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import Adapter.Adapter_huifang;
import Been.QifeiriqiListbeen;
import Been.been_huifang;
import Util.DateUtil;
import Util.JsonUtil;
import Util.NavigationBarUtil;
import Util.PreferenceUtil;
import Util.TimeUtil;
import Util.ToastUtil;
import okhttp3.Call;
import okhttp3.Response;

public class HuiFangList extends AppCompatActivity {

    private String token_str;//用户的token
    Adapter_huifang adapter_huifang;
    RecyclerView recyclerView;
    List<been_huifang> list;
    ArrayList arrayList_detail;

    View nodata;
    Context context = HuiFangList.this;
    String str_st,str_ed;
    TextView tv_starttime,tv_endtime;
    long st,ed;
    private List<String> times = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hui_fang_list);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //  getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

        }


        if (NavigationBarUtil.hasNavigationBar(this)) {
            NavigationBarUtil.initActivity(findViewById(android.R.id.content));//解决底部适配
        }

        token_str = PreferenceUtil.getString("token", "");
        nodata = (View) findViewById(R.id.nodata);
        tv_starttime = (TextView)findViewById(R.id.start_time);
        tv_endtime = (TextView)findViewById(R.id.end_time);
        tv_starttime.setText(DateUtil.getCurDate("yyyy-MM-dd"));
        tv_endtime.setText(DateUtil.getCurDate("yyyy-MM-dd"));
        st = DateUtil.getStringToDate(tv_starttime.getText().toString(),"yyyy-MM-dd")/1000;
        ed = DateUtil.getStringToDate(tv_endtime.getText().toString(),"yyyy-MM-dd")/1000;
        Log.e("时间", String.valueOf(st));
        list = new ArrayList<>();
        arrayList_detail = new ArrayList();
        recyclerView = (RecyclerView) findViewById(R.id.recycler);

        getTimes();


    }
    public void click_starttime(View view){

        //选择开始时间
        Intent intent = new Intent(HuiFangList.this,ChooseriqiActivity.class);
        QifeiriqiListbeen qifeiriqiListbeen = new QifeiriqiListbeen();
        qifeiriqiListbeen.times = times;
        intent.putExtra("times",qifeiriqiListbeen);
        startActivityForResult(intent,2);

    }

    public void click_endtime(View view){
       //选择结束时间

        Intent intent = new Intent(HuiFangList.this,ChooseriqiActivity.class);
        QifeiriqiListbeen qifeiriqiListbeen = new QifeiriqiListbeen();
        qifeiriqiListbeen.times = times;
        intent.putExtra("times",qifeiriqiListbeen);
        startActivityForResult(intent,3);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK ) {
            switch (requestCode){
                case 2:
                    if (!data.getStringExtra("chooseriqi").equals("")){
                        String chooseriqi = data.getStringExtra("chooseriqi");
                        Long choosetime = Long.valueOf(chooseriqi);


                        //获取一次起飞日期后，还需重新获取一次飞行记录，要考虑是否有选择了公司
                        st = choosetime / 1000;

                        if(st>ed){
                            ToastUtil.toast(context,"开始时间不得大于结束时间");
                        }else {
                            tv_starttime.setText(TimeUtil.millis2String(choosetime,new SimpleDateFormat("yyyy-MM-dd")));
                            init();
                        }

                    }
                    break;
                case 3:
                    if (!data.getStringExtra("chooseriqi").equals("")){
                        String chooseriqi = data.getStringExtra("chooseriqi");
                        Long choosetime = Long.valueOf(chooseriqi);


                        //获取一次起飞日期后，还需重新获取一次飞行记录，要考虑是否有选择了公司
                        ed = choosetime / 1000;
                        if(st == 0){
                            ToastUtil.toast(context,"请先选择开始时间");
                        }else if(st>ed){
                            ToastUtil.toast(context,"开始时间不得大于结束时间");
                        }else {
                            tv_endtime.setText(TimeUtil.millis2String(choosetime,new SimpleDateFormat("yyyy-MM-dd")));
                            init();
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    }


    public void init() {

        list.clear();
        MyLoading.show(context);
        try {
            String url = getString(R.string.url) + "/playback/index";

            OkHttpUtils.get(url)
                    .connTimeOut(10000)
                    .params("token", token_str)
                    .params("type","1")
                    .params("st", String.valueOf(st))
                   // .params("ed", String.valueOf(ed))
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(String s, okhttp3.Call call, Response response) {
                            MyLoading.cancel();
                            Object object = null;
                            object = JsonUtil.jsonParse(s);
                            if (object instanceof HashMap) {
                                final HashMap hashMap = (HashMap) object;
                                if (hashMap.containsKey("err")) ;
                                int err = Integer.valueOf(hashMap.get("err").toString());
                                if (err == 0) {
                                    ArrayList lists = (ArrayList) hashMap.get("list");
                                    arrayList_detail = (ArrayList) hashMap.get("list");
                                    if (lists.size() > 0) {
                                        for (int i = 0; i < lists.size(); i++) {
                                            HashMap hashMap1 = (HashMap) lists.get(i);
                                            String id = hashMap1.get("id").toString();
                                            String chepai = hashMap1.get("car_no").toString();
                                            String time = DateUtil.getDateToString((long)Integer.valueOf(hashMap1.get("st").toString()),"yyyy-MM-dd HH:mm")
                                                    +"-"
                                                    +DateUtil.getDateToString((long)Integer.valueOf(hashMap1.get("ed").toString()),"yyyy-MM-dd HH:mm");

                                            been_huifang been = new been_huifang(id,chepai,time);
                                            list.add(been);


                                        }

                                    }


                                } else if (err < 0) {
                                    ReLogin.login(context);
                                } else {
                                    ToastUtil.toast(context, hashMap.get("msg").toString());
                                }

                                LinearLayoutManager linearLayoutManager = new LinearLayoutManager(HuiFangList.this);
                                recyclerView.setLayoutManager(linearLayoutManager);
                                adapter_huifang = new Adapter_huifang(list);
                                recyclerView.setAdapter(adapter_huifang);

                                adapter_huifang.setItemClick(new Adapter_huifang.item_click() {
                                    @Override
                                    public void itemclick(int position) {
                                        //点击播放
                                        HashMap hashMap1 = (HashMap)arrayList_detail.get(position);

                                        Intent intent = new Intent(HuiFangList.this,HuiFang.class);
                                        intent.putExtra("st",hashMap1.get("st").toString());
                                        intent.putExtra("ed",hashMap1.get("ed").toString());
                                        intent.putExtra("id",hashMap1.get("id").toString());
                                        startActivity(intent);


                                    }
                                });


                                if (list.size() == 0) {
                                    recyclerView.setVisibility(View.GONE);
                                    nodata.setVisibility(View.VISIBLE);
                                } else {
                                    recyclerView.setVisibility(View.VISIBLE);
                                    nodata.setVisibility(View.GONE);
                                }


                            }

                        }

                        @Override
                        public void onError(Call call, Response response, Exception e) {

                            MyLoading.cancel();
                            Toast.makeText(HuiFangList.this, "连接服务器失败", Toast.LENGTH_LONG).show();
                            e.printStackTrace();
                        }
                    });

        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    public void getTimes(){

        MyLoading.show(context);
        try {
            String url = getString(R.string.url) + "/playback/times";

            OkHttpUtils.get(url)
                    .connTimeOut(10000)
                    .params("token",token_str)
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(String s, okhttp3.Call call, Response response) {
                            MyLoading.cancel();
                            Object object = null;
                            object = JsonUtil.jsonParse(s);
                            if(object instanceof HashMap) {
                                HashMap hashMap = (HashMap) object;
                                if (hashMap.containsKey("err")) ;
                                int err = Integer.valueOf(hashMap.get("err").toString());
                                if (err == 0) {

                                    times = (ArrayList) hashMap.get("times");
                                    init();

                                }else if(err < 0){
                                    ReLogin.login(context);
                                }else {
                                    ToastUtil.toast(context,hashMap.get("msg").toString());
                                }




                            }

                        }
                        @Override
                        public void onError(Call call, Response response, Exception e) {

                            Toast.makeText(HuiFangList.this, "连接服务器失败", Toast.LENGTH_LONG).show();
                            e.printStackTrace();
                        }
                    });

        }catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void click_back(View view){
        finish();
    }

}
